package context.dao;

import context.model.Comment;
import context.model.Dynamic;
import context.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import javax.servlet.http.HttpSession;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Repository
public class DynamicRepository {
    private final String SELECT_BY_ID = "SELECT * FROM contest.dynamic  join contest.user on dynamic.userid=contest.user.id join userinformation on dynamic.userid=userinformation.userid  where dynamic.dynamic_id=?";
    private final String INSERT_USER = "insert into dynamic(userid,dynamic_word,dynamic_image,dynamic_video,dynamic_date) values(?,?,?,?,?)";

    private JdbcTemplate jdbcTemplate;

    private Connection connection;
    @Autowired          //自动装配
    public DynamicRepository(JdbcTemplate jdbcTemplate) throws SQLException {
        this.jdbcTemplate = jdbcTemplate;
        connection = jdbcTemplate.getDataSource().getConnection();
    }


    @Autowired
    private UserRepository mUserRepotory;

    @Autowired
    private CommentRepository mCommentRepository;

    @Autowired
    private Thumbs_upRepository thumbs_upRepository;

    @Autowired
    HttpSession session;

    private Dynamic mapRow(ResultSet resultSet) throws SQLException {
        Dynamic result = new Dynamic();
        result.setUserid(resultSet.getLong("userid"));
        result.setDynamic_id(resultSet.getLong("dynamic_id"));
        result.setDynamic_word(resultSet.getString("dynamic_word"));
        result.setDynamic_image(resultSet.getString("dynamic_image"));
        result.setDynamic_video(resultSet.getString("dynamic_video"));
        result.setDynamic_date(resultSet.getString("dynamic_date"));
        result.setFollow_dynamic_id(resultSet.getLong("follow_dynamic_id"));

        User user = new User();
        user.setId(resultSet.getLong("id"));
        user.setUserimg(resultSet.getString("img"));
        user.setUsername(resultSet.getString("username"));

        result.setUser(user);
        result.setCommentList(mCommentRepository.getDynamicCommnents(result.getDynamic_id()));

        result.setThumbCount(thumbs_upRepository.findThumbsCountByID(result.getDynamic_id()));  //点赞次数
        Long userid = (Long) session.getAttribute("userid");
        System.out.println(userid);
        if (userid == null) {
            result.setThumb(false);
        } else {
            int i = thumbs_upRepository.findThumbsByID(userid, result.getDynamic_id());
            System.out.println("点赞：" + i);
            if (i == 0) {       //查询当前的用户是否给这条动态点赞
                result.setThumb(false);
            } else {
                result.setThumb(true);
            }
        }

        if (result.getFollow_dynamic_id() != 0) {  //转发的其他动态
            Dynamic forwardDynamic = findDynamicByID(result.getFollow_dynamic_id());
            result.setForwardDynamic(forwardDynamic);
        }

        return result;
    }


    //查
    public Dynamic findDynamicByID(long id) {
        Dynamic dynamic = null;        //构建一个list,保存动态

        try {
//            Connection connection = jdbcTemplate.getDataSource().getConnection(); //获得数据库连接

            PreparedStatement preparedStatement = connection.prepareStatement(SELECT_BY_ID);  //创建预备语句
            preparedStatement.setLong(1, id);        //设置sql语句中的参数值
            ResultSet resultSet = preparedStatement.executeQuery();       //查询
            if (resultSet.next()) {       //循环遍历结果集
                dynamic = mapRow(resultSet);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return dynamic;
    }


    //增
    public int insertDynamic(final long userid, final String dynamic_word, final String dynamic_image, final String dynamic_video, final Timestamp dynamic_date) {

        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(
                new PreparedStatementCreator() {
                    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                        PreparedStatement ps = con.prepareStatement(INSERT_USER, new String[]{"userid", "dynamic_word", "dynamic_image", "dynamic_video", "dynamic_date"});
                        ps.setLong(1, userid);
                        ps.setString(2, dynamic_word);
                        ps.setString(3, dynamic_image);
                        ps.setString(4, dynamic_video);
                        ps.setTimestamp(5, dynamic_date);
                        return ps;
                    }
                }, keyHolder);
        System.out.println("自动插入id============================" + keyHolder.getKey().intValue());
        return keyHolder.getKey().intValue();
    }

    //删
    private static final String sql = "delete  from dynamic where userid = ?";

    public void delete(int dynamic_id) {
        Object[] obj = new Object[]{dynamic_id};
        int i = jdbcTemplate.update(sql, obj);

        if (i > 0) {
            System.out.println("删除成功");
        } else {
            System.out.println("删除失败");
        }
    }

    private static final String SELECT_DYNAMIC = "SELECT * FROM contest.dynamic  join contest.user on dynamic.userid=contest.user.id join userinformation on dynamic.userid=userinformation.userid   where dynamic_date between ? and now() order by dynamic_date desc ";

    public List<Dynamic> getDynamicListBeforeTime(Timestamp timestamp) {        //随机取动态 用于主页中获取
        List<Dynamic> dynamics = new ArrayList<>();

        try {
//            Connection connection = jdbcTemplate.getDataSource().getConnection();

            PreparedStatement statement = connection.prepareStatement(SELECT_DYNAMIC);
            ResultSet resultSet = statement.executeQuery();

            while (resultSet.next()) {
                Dynamic dynamic = mapRow(resultSet);
                dynamics.add(dynamic);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return dynamics;
    }

    private static String SELECT_FIRST_TEN = "SELECT * FROM contest.dynamic join contest.user on dynamic.userid=contest.user.id join userinformation on dynamic.userid=userinformation.userid  order by dynamic.dynamic_date desc limit 10";

    public List<Dynamic> getFirstTenDynamic() {
        List<Dynamic> dynamics = new ArrayList<>();
        try {
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(SELECT_FIRST_TEN);
            while (resultSet.next()) {
                Dynamic dynamic = mapRow(resultSet);
                dynamics.add(dynamic);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return dynamics;
    }

    private static String Forward_State = "insert into dynamic(userid,dynamic_word,dynamic_date,follow_dynamic_id) values(?,?,?,?)";

    public int forwardState(long userid, String content, long dynamicID) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(
                new PreparedStatementCreator() {
                    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                        PreparedStatement ps = con.prepareStatement(Forward_State, new String[]{"userid", "dynamic_word", "dynamic_date", "follow_dynamic_id"});
                        ps.setLong(1, userid);
                        ps.setString(2, content);
                        ps.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
                        ps.setLong(4, dynamicID);
                        return ps;
                    }
                }, keyHolder);
        System.out.println("自动插入id============================" + keyHolder.getKey().intValue());
        return keyHolder.getKey().intValue();
    }


    private String ATTENTION_STATE = "SELECT * FROM contest.follow right join dynamic on dynamic.userid=follow.follow_userid left join userinformation on follow.follow_userid=userinformation.userid where follow.userid=?";

    public List<Dynamic> getMyAttentionState(long userid) {
        List<Dynamic> dynamics = new ArrayList<>();

        try {
//            Connection connection = jdbcTemplate.getDataSource().getConnection();

            PreparedStatement statement = connection.prepareStatement(ATTENTION_STATE);
            statement.setLong(1, userid);
            ResultSet resultSet = statement.executeQuery();

            while (resultSet.next()) {
                Dynamic dynamic = mapRow(resultSet);
                dynamics.add(dynamic);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return dynamics;
    }

}
